package com.shushan.exercise;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.BaseExerciseHeaderActivity;
import com.shushan.base.Constants;
import com.shushan.home.bean.RewardTimeBean;
import com.shushan.home.bean.RewardToyBean;
import com.shushan.mixedexam.MixedExamActivity;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.pages.StudyProgressSetActivity;
import com.shushan.pages.bean.SubjectSyncExerciseBean;
import com.shushan.pages.bean.SyncExerciseDetailBean;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.util.DialogUtil;
import com.shushan.util.ImageUtils;
import com.shushan.util.Session;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * @ClassName: SyncExerciseActivity
 * @Desciption: //同步练习展示界面
 * @author: zhangshihao
 * @date: 2018-04-11
 */
public class SyncExerciseActivity extends BaseExerciseHeaderActivity implements View.OnClickListener {

    private static final String TAG = SyncExerciseActivity.class.getSimpleName();

    private ImageView ivToyPic;
    private ImageView ivChineseBook;
    private ImageView ivMathBook;
    private ImageView ivEnglishBook;

    private TextView tvToyName;
    private TextView tvCompleteCondition;
    private TextView tvProgressNowChinese;
    private TextView tvProgressNowMath;
    private TextView tvProgressNowEnglish;

    private LinearLayout llsetProgressChinese;
    private LinearLayout llsetProgressMath;
    private LinearLayout llsetProgressEnglish;
    private LinearLayout llpreLessonChinese;
    private LinearLayout llnextLessonChinese;
    private LinearLayout llpreLessonMath;
    private LinearLayout llnextLessonMath;
    private LinearLayout llpreLessonEnglish;
    private LinearLayout llnextLessonEnglish;

    private RelativeLayout rlChinese;
    private RelativeLayout rlMath;
    private RelativeLayout rlEnglish;

    private Button btnStartExercise;
    private Dialog continueDialog;

    private int progress_lock;

    private SubjectSyncExerciseBean chineseSyncExerciseBean;
    private SubjectSyncExerciseBean mathSyncExerciseBean;
    private SubjectSyncExerciseBean englishSyncExerciseBean;
    private BabyApplication shuShanApplication = BabyApplication.getInstance();
    private int awardType;//1(同步练习)   14(语文专项练习) 15（数学专项练习）16（英语专项练习）
    private int clickId;

    private RewardToyBean rewardToyBean;
    private RewardTimeBean rewardTimeBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sync_exercise);

        Intent intent = getIntent();
        awardType = intent.getIntExtra("awardType", 1);
        rewardTimeBean = (RewardTimeBean) Session.getSession().get("rewardTimeBean");
        rewardToyBean = (RewardToyBean) Session.getSession().get("rewardToyBean");

        if(awardType == Constants.TYPE_SYNC_EXERCISE){
            setTitle("同步练习");
        }else if(awardType == Constants.TYPE_CHINESE_SECT_EXERCISE){
            setTitle("语文分科练习");
        }else if(awardType == Constants.TYPE_MACH_SECT_EXERCISE){
            setTitle("数学分科练习");
        }else if(awardType == Constants.TYPE_ENGLISH_SECT_EXERCISE){
            setTitle("英语分科练习");
        }

        initView();
    }

    private void initView(){
        ivToyPic = findViewById(R.id.iv_toy_pic);
        ivChineseBook = findViewById(R.id.iv_chinese_book);
        ivMathBook = findViewById(R.id.iv_math_book);
        ivEnglishBook = findViewById(R.id.iv_english_book);

        tvToyName = findViewById(R.id.tv_toy_name);
        tvCompleteCondition = findViewById(R.id.tv_complete_condition);
        tvProgressNowChinese = findViewById(R.id.tv_progress_now_chinese);
        tvProgressNowMath = findViewById(R.id.tv_progress_now_math);
        tvProgressNowEnglish = findViewById(R.id.tv_progress_now_english);

        llsetProgressChinese = findViewById(R.id.ll_set_progress_chinese);
        llsetProgressMath = findViewById(R.id.ll_set_progress_math);
        llsetProgressEnglish = findViewById(R.id.ll_set_progress_english);
        llpreLessonChinese = findViewById(R.id.ll_pre_lesson_chinese);
        llpreLessonMath = findViewById(R.id.ll_pre_lesson_math);
        llpreLessonEnglish = findViewById(R.id.ll_pre_lesson_english);
        llnextLessonChinese = findViewById(R.id.ll_next_lesson_chinese);
        llnextLessonMath = findViewById(R.id.ll_next_lesson_math);
        llnextLessonEnglish = findViewById(R.id.ll_next_lesson_english);

        rlChinese = findViewById(R.id.rl_chinese);
        rlMath = findViewById(R.id.rl_math);
        rlEnglish = findViewById(R.id.rl_english);

        btnStartExercise = findViewById(R.id.btn_start_exercise);

        llsetProgressChinese.setOnClickListener(this);
        llsetProgressMath.setOnClickListener(this);
        llsetProgressEnglish.setOnClickListener(this);
        llpreLessonChinese.setOnClickListener(this);
        llpreLessonMath.setOnClickListener(this);
        llpreLessonEnglish.setOnClickListener(this);
        llnextLessonChinese.setOnClickListener(this);
        llnextLessonMath.setOnClickListener(this);
        llnextLessonEnglish.setOnClickListener(this);

        btnStartExercise.setOnClickListener(this);

        if(awardType == 1 && rewardTimeBean != null){
                ivToyPic.setImageResource(R.drawable.ic_time_award);
                tvToyName.setText("获得手机使用时间");
                tvCompleteCondition.setText(rewardTimeBean.task);
        }else if(awardType != 1 && rewardToyBean != null){
            ImageUtils.loadWXImageView(this,rewardToyBean.pic,ivToyPic);
            tvToyName.setText(rewardToyBean.name);
            tvCompleteCondition.setText(rewardToyBean.getDescription_list().get(0));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    @Override
    protected void onStop() {
        super.onStop();

        if(continueDialog != null){
            continueDialog.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_set_progress_chinese://设置语文进度
                gotoSetProgress(1);
                break;
            case R.id.ll_set_progress_math://设置数学进度
                gotoSetProgress(2);
                break;
            case R.id.ll_set_progress_english:////设置英语进度
                gotoSetProgress(3);
                break;
            case R.id.ll_pre_lesson_chinese://语文上一课
                clickId = R.id.ll_pre_lesson_chinese;
                setProgress(Constants.SUBJECT_CHINESE_ID,1);
                break;
            case R.id.ll_pre_lesson_math://数学上一课
                clickId = R.id.ll_pre_lesson_math;
                setProgress(Constants.SUBJECT_MACH_ID,1);
                break;
            case R.id.ll_pre_lesson_english://英语上一课
                clickId = R.id.ll_pre_lesson_english;
                setProgress(Constants.SUBJECT_ENGLISH_ID,1);
                break;
            case R.id.ll_next_lesson_chinese://语文下一课
                clickId = R.id.ll_next_lesson_chinese;
                setProgress(Constants.SUBJECT_CHINESE_ID,2);
                break;
            case R.id.ll_next_lesson_math://数学下一课
                clickId = R.id.ll_next_lesson_math;
                setProgress(Constants.SUBJECT_MACH_ID,2);
                break;
            case R.id.ll_next_lesson_english://英语下一课
                clickId = R.id.ll_next_lesson_english;
                setProgress(Constants.SUBJECT_ENGLISH_ID,2);
                break;
            case R.id.btn_start_exercise://开始练习
                if(!isAllUse(awardType)){
                    DialogUtil.showNoVipDialog(this,Constants.TYPE_SYNC_EXERCISE);
                    return;
                }
                Session.getSession().put("rewardTimeBean",rewardTimeBean);
                Session.getSession().put("rewardToyBean",rewardToyBean);

                Intent intent = new Intent(this,MixedExamActivity.class);
                intent.putExtra("examType",awardType);
                startActivityForResultAllow(intent);
                break;
            default:
                break;
        }
    }


    private void gotoSetProgress(int tpye) {
        if(progress_lock == 0){
            showToast("学生不可以调节进度");
            return;
        }

        if(tpye == 1 && chineseSyncExerciseBean != null){
            Intent intent = new Intent(this,StudyProgressSetActivity.class);
            intent.putExtra("pressName",chineseSyncExerciseBean.press_name);
            intent.putExtra("subjectId",Constants.SUBJECT_CHINESE_ID);
            intent.putExtra("outlineId",chineseSyncExerciseBean.outline_id);
            intent.putExtra("outlineDetailId",chineseSyncExerciseBean.outline_detail_id);
            intent.putExtra("practiceType",Constants.TYPE_SYNC_EXERCISE);
            startActivityForResultAllow(intent);
        }else if(tpye == 2 && mathSyncExerciseBean != null){
            Intent intent = new Intent(this,StudyProgressSetActivity.class);
            intent.putExtra("subjectId",Constants.SUBJECT_MACH_ID);
            intent.putExtra("outlineId",mathSyncExerciseBean.outline_id);
            intent.putExtra("outlineDetailId",mathSyncExerciseBean.outline_detail_id);
            intent.putExtra("practiceType",Constants.TYPE_SYNC_EXERCISE);
            startActivityForResultAllow(intent);
        }else if(tpye == 3 && englishSyncExerciseBean != null){
            Intent intent = new Intent(this,StudyProgressSetActivity.class);
            intent.putExtra("subjectId",Constants.SUBJECT_ENGLISH_ID);
            intent.putExtra("outlineId",englishSyncExerciseBean.outline_id);
            intent.putExtra("outlineDetailId",englishSyncExerciseBean.outline_detail_id);
            intent.putExtra("practiceType",Constants.TYPE_SYNC_EXERCISE);
            startActivityForResultAllow(intent);
        }
    }

    /**
     * 设置下一课和上一课
     * @param subjectId
     * @param type 1:上一课；2下一课
     */
    private void setProgress(int subjectId, int type) {
        if(progress_lock == 0){
            showToast("学生不可以调节进度");
            return;
        }

        int childId = shuShanApplication.getCurrentChildId();

        int outline_id = 0;
        int outline_detail_id = 0;
        if(subjectId == Constants.SUBJECT_CHINESE_ID && chineseSyncExerciseBean != null){
            outline_id = chineseSyncExerciseBean.outline_id;
            outline_detail_id = chineseSyncExerciseBean.outline_detail_id;
        }else if(subjectId == Constants.SUBJECT_MACH_ID && mathSyncExerciseBean != null){
            outline_id = mathSyncExerciseBean.outline_id;
            outline_detail_id = mathSyncExerciseBean.outline_detail_id;
        }else if(subjectId == Constants.SUBJECT_ENGLISH_ID && englishSyncExerciseBean != null){
            outline_id = englishSyncExerciseBean.outline_id;
            outline_detail_id = englishSyncExerciseBean.outline_detail_id;
        }

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.SET_NEXT_PRE_PROGRESS);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("subject_id", subjectId + "")
                .putValue("child_id", childId)
                .putValue("type", type + "")
                .putValue("outline_id", outline_id + "")
                .putValue("outline_detail_id", outline_detail_id + "")
                .putValue("practice_type",Constants.TYPE_SYNC_EXERCISE);
        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(String data) {
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(data);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        if(jsonObject != null){
                            int outlineDetailId = jsonObject.optInt("outline_detail_id",0);
                            String outlineName = jsonObject.optString("outline_name","");
                            setSwitchProgress(outlineDetailId,outlineName);

                            if (!shuShanApplication.isSectVip(Constants.TYPE_SYNC_EXERCISE)){
                                getData();
                            }

                        }

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {

                        showNetError(netRetBean);
                    }
                });
    }


    private void setSwitchProgress(int outlineDetailId, String outlineName){
        if(TextUtils.isEmpty(outlineName) || outlineDetailId <= 0){
            return;
        }

        switch (clickId){
            case R.id.ll_pre_lesson_chinese://语文上一课
            case R.id.ll_next_lesson_chinese://语文下一课
                tvProgressNowChinese.setText("当前进度：" + outlineName);
                chineseSyncExerciseBean.outline_detail_id = outlineDetailId;
                chineseSyncExerciseBean.outline_detail_name = outlineName;
                break;
            case R.id.ll_pre_lesson_math://数学上一课
            case R.id.ll_next_lesson_math://数学下一课
                tvProgressNowMath.setText("当前进度：" + outlineName);
                mathSyncExerciseBean.outline_detail_id = outlineDetailId;
                mathSyncExerciseBean.outline_detail_name = outlineName;
                break;
            case R.id.ll_pre_lesson_english://英语上一课
            case R.id.ll_next_lesson_english://英语下一课
                tvProgressNowEnglish.setText("当前进度：" + outlineName);
                englishSyncExerciseBean.outline_detail_id = outlineDetailId;
                englishSyncExerciseBean.outline_detail_name = outlineName;
                break;
            default:
                break;
        }
    }

    private void getData(){
        int childId = shuShanApplication.getCurrentChildId();
        showWaitDialog();

        UrlParse urlParse = new UrlCommParse(this,UrlConst.BASE_URL);
        UrlParse paramParse = new UrlCommParse(this).putValue("child_id", childId);
        final int exerciseType;
        if(awardType == Constants.TYPE_SYNC_EXERCISE){
            urlParse.appendRegion(UrlConst.MUTIPLE_TYPES_LIST);
            exerciseType = Constants.TYPE_SYNC_EXERCISE;
        }else {
            urlParse.appendRegion(UrlConst.SPECIALTY_TYPES_LIST);
            exerciseType = awardType;

        }

        paramParse.putValue("practice_type",exerciseType);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<SyncExerciseDetailBean>() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(SyncExerciseDetailBean syncExerciseDetailBean) {
                        if(syncExerciseDetailBean == null) {
                            return;
                        }

                        int paperId = syncExerciseDetailBean.paper_id;
                        if(paperId > 0){
                            continueDialog = ContinueExerciseHelp.showContinueDialog(SyncExerciseActivity.this,exerciseType,paperId);
                        }

                        progress_lock = syncExerciseDetailBean.progress_lock;
                        chineseSyncExerciseBean = syncExerciseDetailBean.chineseSyncExerciseBean;
                        mathSyncExerciseBean = syncExerciseDetailBean.mathSyncExerciseBean;
                        englishSyncExerciseBean = syncExerciseDetailBean.englishSyncExerciseBean;

                        updateUIbyData(syncExerciseDetailBean);

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private boolean isAllUse(int awardType) {
        boolean isAllChineseUse = true;
        boolean isAllMathUse = true;
        boolean isAllEnglishUse = true;
        if(chineseSyncExerciseBean != null){
            isAllChineseUse =  (chineseSyncExerciseBean.state==0);
        }

        if(mathSyncExerciseBean != null){
            isAllMathUse =  (mathSyncExerciseBean.state==0);
        }

        if(englishSyncExerciseBean != null){
            isAllEnglishUse =  (englishSyncExerciseBean.state==0);
        }

        boolean isAllUse = false;
        if(awardType == Constants.TYPE_SYNC_EXERCISE){
            isAllUse = isAllChineseUse && isAllMathUse && isAllEnglishUse;
        }else if (awardType == Constants.TYPE_CHINESE_SECT_EXERCISE){
            isAllUse = isAllChineseUse;
        }else if (awardType == Constants.TYPE_MACH_SECT_EXERCISE){
            isAllUse = isAllMathUse;
        }else if (awardType == Constants.TYPE_ENGLISH_SECT_EXERCISE){
            isAllUse = isAllEnglishUse;
        }

        return (shuShanApplication.isSectVip(Constants.TYPE_SYNC_EXERCISE) || isAllUse);
    }

    private void updateUIbyData(SyncExerciseDetailBean syncExerciseDetailBean){
        setHeaderText(shuShanApplication.getCurrentChildBean(),syncExerciseDetailBean.score,syncExerciseDetailBean.time);

        if(chineseSyncExerciseBean != null){
            rlChinese.setVisibility(View.VISIBLE);
            tvProgressNowChinese.setText("当前进度：" + chineseSyncExerciseBean.outline_detail_name);
            ImageUtils.loadImageView(this,chineseSyncExerciseBean.outline_cover,ivChineseBook);
        }else{
            rlChinese.setVisibility(View.GONE);
        }
        if(mathSyncExerciseBean != null){
            rlMath.setVisibility(View.VISIBLE);
            tvProgressNowMath.setText("当前进度：" + mathSyncExerciseBean.outline_detail_name);
            ImageUtils.loadImageView(this,mathSyncExerciseBean.outline_cover,ivMathBook);
        }else{
            rlMath.setVisibility(View.GONE);
        }
        if(englishSyncExerciseBean != null){
            rlEnglish.setVisibility(View.VISIBLE);
            tvProgressNowEnglish.setText("当前进度：" + englishSyncExerciseBean.outline_detail_name);
            ImageUtils.loadImageView(this,englishSyncExerciseBean.outline_cover,ivEnglishBook);
        }else{
            rlEnglish.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.i(TAG,"resultCode=" + resultCode);
        if(resultCode == 100){
            getData();
        }else if(resultCode == 200){
            onBackAction();
        }
    }
}
